package com.yiren.manager.utils;


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.springframework.util.StringUtils;

/**
 * Created by yanwenhao on 17-10-16
 */
public class ObjectUtils {
    /**
     * create by yanwenhao
     * 将一个对象转化为另一个对象
     * @param o 待转换的对象
     * @param cls 转换后的对象类型
     * @return
     * @throws IllegalAccessException 
     * @throws InstantiationException 
     * @throws InvocationTargetException 
     * @throws IllegalArgumentException 
     */
    public static <T> T objectToObject(Object form ,Class<T> to) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
    	T t = to.newInstance();
    	
    	Method[] formMethods = form.getClass().getDeclaredMethods();
    	
    	Map<String, Method> getMap = new HashMap<String, Method>();
    	for(Method method : formMethods){
    		if(method.getName().startsWith("get")){
    			getMap.put(method.getName().substring(3), method);
    		}
    	}
    	Method[] toMethods = to.getDeclaredMethods();
    	for(Method method : toMethods){
    		if(method.getName().startsWith("set")){
    			if(getMap.containsKey(method.getName().substring(3))){
    				if(!StringUtils.isEmpty(getMap.get(method.getName().substring(3)).invoke(form))){
    					method.invoke(t, getMap.get(method.getName().substring(3)).invoke(form));	
    				}
    			}
    		}
    	}
    	return t;
    }
    
    /**
     * create by yanwenhao
     * 将一个对象转化为另一个对象
     * @param o 待转换的对象
     * @param cls 转换后的对象类型
     * @return
     * @throws IllegalAccessException 
     * @throws InstantiationException 
     * @throws InvocationTargetException 
     * @throws IllegalArgumentException 
     */
    public static  <T> T objectToObjectWithOutNull(T form ,T to) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{

    	Method[] formMethods = form.getClass().getDeclaredMethods();
    	
    	Map<String, Method> getMap = new HashMap<String, Method>();
    	for(Method method : formMethods){
    	   	if(method.getName().startsWith("get")){
        		getMap.put(method.getName().substring(3), method);
    		}
    	}
    	Method[] toMethods = to.getClass().getDeclaredMethods();
    	for(Method method : toMethods){
    		if(method.getName().startsWith("set")){
    			if(getMap.containsKey(method.getName().substring(3))){
    				if(!StringUtils.isEmpty(getMap.get(method.getName().substring(3)).invoke(form))){
    					method.invoke(to, getMap.get(method.getName().substring(3)).invoke(form));	
    				}
    			}
    		}
    	}
    	return to;
    }
}
